﻿//-----------------------------------------------------------------------
// <copyright file="TenancyRepository.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Infrastructure.Win2K8WithSQLServer.Repositories{    using System;
    using System.Collections.Generic;
    using System.Linq;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.ValueObjects;
    using AbstractSaaSTemplate.Domain.Repositories;

    /// <summary>
    /// Implements 'ITemplatesRepository' and all its contract, providing
    /// data accessibility to the aggregate 'Templates'.
    /// </summary>
    public sealed class TenancyRepository : SQLServerConnectedRepositoryBase, ITenancyRepository
    {
        /// <summary>
        /// Initializes a new instance of the TenancyRepository class.
        /// </summary>
        /// <param name="loaderForConnectionString">The delegate capable of retrieving the connection string for the LinQ2SQL context.</param>
        public TenancyRepository(Func<string> loaderForConnectionString)
            : base(loaderForConnectionString)
        {
        }

        /// <summary>
        /// Gets a list of all entries of 'Tenant' available in the system.
        /// </summary>
        /// <returns>Returns a list of Tenant.</returns>
        public IEnumerable<Tenant> Tenants
        {
            get
            {
                using (var context = NewContext())
                {
                    var tenants = context.Tenants
                        .ToArray();

                    var entities = new List<Tenant>(tenants.Length);
                    foreach (var tenant in tenants)
                    {
                        var entity = this.GetTenantById(tenant.Id);
                        entities.Add(entity);
                    }

                    return entities;
                }
            }
        }

        /// <summary>
        /// Creates or updates a 'Tenant' in the system.
        /// </summary>
        /// <param name="entity">The entry of 'Tenant' which will be either created or updated.</param>
        public void AddOrUpdateTenant(Tenant entity)
        {
            using (var context = NewContext())
            {
                var tenant = context.Tenants
                    .Where(d => d.Id == entity.Id)
                    .FirstOrDefault();

                if (tenant == null)
                {
                    tenant = new Core.Tenant();
                    tenant.Key = entity.Key;
                    context.Tenants.AddObject(tenant);
                }

                CopyFromDomainToEF4<Tenant, Core.Tenant>(
                    entity,
                    tenant);

                // we save all changes
                context.SaveChanges();

                // retrieves identity generated by the database.
                entity.Id = tenant.Id;

                // work with the value objects attached to the domain
                this.CreateOrUpdateAddressForTenant(entity.Id, entity.BillingAddress, AddressTypes.Billing);
                this.CreateOrUpdateAddressForTenant(entity.Id, entity.ContactAddress, AddressTypes.Contact);
                this.CreateOrUpdatePhoneForTenant(entity.Id, entity.ContactPhone);
                this.CreateOrUpdateInstanceSetupForTenant(entity.Id, entity.InstanceSetup);
            }
        }

        /// <summary>
        /// Retrieves a tenant by its Id.
        /// </summary>
        /// <param name="id">The if of the tenant.</param>
        /// <returns>If a tenant matches the Id, returns it; otherwise, returns null.</returns>
        public Tenant GetTenantById(long id)
        {
            using (var context = NewContext())
            {
                var tenant = context.Tenants
                    .Where(d => d.Id == id)
                    .FirstOrDefault();

                if (tenant == null)
                {
                    return null;
                }

                var entity = new Tenant();
                entity.Id = tenant.Id;
                entity.Key = tenant.Key;

                CopyFromEF4ToDomain<Core.Tenant, Tenant>(
                    tenant,
                    entity);

                var billingAddress = context.Addresses
                    .Where(d =>
                        (d.TenantId.HasValue && d.TenantId == entity.Id) &&
                        (d.Type == AddressTypes.Billing))
                    .FirstOrDefault();

                var contactAddress = context.Addresses
                    .Where(d =>
                        (d.TenantId.HasValue && d.TenantId == entity.Id) &&
                        (d.Type == AddressTypes.Contact))
                    .FirstOrDefault();

                var phone = context.Phones
                    .Where(d => d.TenantId.HasValue && d.TenantId == entity.Id)
                    .FirstOrDefault();

                var instanceSetup = context.InstanceSetups
                    .Where(d => d.TenantId.HasValue && d.TenantId == entity.Id)
                    .FirstOrDefault();

                if (billingAddress == null)
                {
                    entity.BillingAddress = new Address();
                }
                else
                {
                    entity.BillingAddress = new Address()
                    {
                        Line1 = billingAddress.Line1,
                        Line2 = billingAddress.Line2,
                        Line3 = billingAddress.Line3,
                        City = billingAddress.City,
                        State = billingAddress.State,
                        CountryCode = billingAddress.CountryCode,
                        PostalCode = billingAddress.PostalCode
                    };
                }
                
                if (contactAddress == null)
                {
                    entity.ContactAddress = entity.BillingAddress;
                }
                else
                {
                    entity.ContactAddress = new Address()
                    {
                        Line1 = contactAddress.Line1,
                        Line2 = contactAddress.Line2,
                        Line3 = contactAddress.Line3,
                        City = contactAddress.City,
                        State = contactAddress.State,
                        CountryCode = contactAddress.CountryCode,
                        PostalCode = billingAddress.PostalCode
                    };
                }

                if (phone == null)
                {
                    entity.ContactPhone = new PhoneNumber();
                }
                else
                {
                    entity.ContactPhone = new PhoneNumber()
                    {
                        AreaCode = phone.AreaCode,
                        Number = phone.Number,
                        Extension = phone.Extension
                    };
                }

                return entity;
            }
        }

        /// <summary>
        /// Retrieves a tenant by its key.
        /// </summary>
        /// <param name="key">The key of the tenant.</param>
        /// <returns>If a tenant matches the key, returns it; otherwise, returns null.</returns>
        public Tenant GetTenantByKey(string key)
        {
            using (var context = NewContext())
            {
                var tenant = context.Tenants
                    .Where(d => d.Key == key)
                    .FirstOrDefault();

                if (tenant == null)
                {
                    return null;
                }

                var entity = new Tenant();
                entity.Id = tenant.Id;
                entity.Key = tenant.Key;

                CopyFromEF4ToDomain<Core.Tenant, Tenant>(
                    tenant,
                    entity);

                return entity;
            }
        }

        /// <summary>
        /// Manages the addresses for the tenant.
        /// </summary>
        /// <param name="tenantId">The id of the tenant for which we will manage the addresses.</param>
        /// <param name="address">The address to be created or updated.</param>
        /// <param name="type">The address type.</param>
        private void CreateOrUpdateAddressForTenant(
            long tenantId,
            Address address,
            string type)
        {
            if (address == null)
            {
                return;
            }
            
            using (var context = NewContext())
            {
                // here we should create the items attached to 
                // the tenant such as phone and address and
                // associate them to it.
                var databaseAddress = context.Addresses
                    .Where(d =>
                        (d.TenantId.HasValue && d.TenantId == tenantId) &&
                        (d.Type == type))
                    .FirstOrDefault();

                if (databaseAddress == null)
                {
                    databaseAddress = new Core.Address();
                    databaseAddress.Id = Guid.NewGuid();
                    databaseAddress.TenantId = tenantId;
                    databaseAddress.CreatedAt = DateTime.Now;
                    context.Addresses.AddObject(databaseAddress);
                }

                databaseAddress.Line1 = address.Line1;
                databaseAddress.Line2 = address.Line2;
                databaseAddress.Line3 = address.Line3;
                databaseAddress.City = address.City;
                databaseAddress.State = address.State;
                databaseAddress.CountryCode = address.CountryCode;
                databaseAddress.PostalCode = address.PostalCode;
                databaseAddress.Type = type;

                context.SaveChanges();
            }
        }

        /// <summary>
        /// Manages the phones for the tenant.
        /// </summary>
        /// <param name="tenantId">The id of the tenant for which we will manage the addresses.</param>
        /// <param name="phone">The phone that we will create or update.</param>
        private void CreateOrUpdatePhoneForTenant(
            long tenantId,
            PhoneNumber phone)
        {
            if (phone == null)
            {
                return;
            }

            using (var context = NewContext())
            {
                // here we should create the items attached to 
                // the tenant such as phone and address and
                // associate them to it.
                var databasePhone = context.Phones
                    .Where(d => (d.TenantId.HasValue && d.TenantId == tenantId))
                    .FirstOrDefault();

                if (databasePhone == null)
                {
                    databasePhone = new Core.Phone();
                    databasePhone.Id = Guid.NewGuid();
                    databasePhone.TenantId = tenantId;
                    databasePhone.CreatedAt = DateTime.Now;
                    context.Phones.AddObject(databasePhone);
                }

                databasePhone.AreaCode = phone.AreaCode;
                databasePhone.Number = phone.Number;
                databasePhone.Extension = phone.Extension;

                context.SaveChanges();
            }
        }

        /// <summary>
        /// Manages the instance setups for the tenant.
        /// </summary>
        /// <param name="tenantId">The id of the tenant.</param>
        /// <param name="instanceSetup">The setup of the instance for the tenant.</param>
        private void CreateOrUpdateInstanceSetupForTenant(
            long tenantId,
            InstanceInfo instanceSetup)
        {
            if (instanceSetup == null)
            {
                instanceSetup = new InstanceInfo();
            }

            using (var context = NewContext())
            {
                var databaseInstanceSetup = context.InstanceSetups
                    .Where(d => d.TenantId.HasValue && d.TenantId == tenantId)
                    .OrderByDescending(d => d.CreatedAt)
                    .FirstOrDefault();

                if (databaseInstanceSetup == null)
                {
                    databaseInstanceSetup = new Core.InstanceSetup();
                    databaseInstanceSetup.Id = Guid.NewGuid();
                    databaseInstanceSetup.TenantId = tenantId;
                    databaseInstanceSetup.CreatedAt = DateTime.Now;
                    context.InstanceSetups.AddObject(databaseInstanceSetup);
                }

                databaseInstanceSetup.ThemeName = instanceSetup.ThemeName;
                databaseInstanceSetup.LayoutName = instanceSetup.LayoutName;
                databaseInstanceSetup.ColorForH1 = instanceSetup.ColorForH1;
                databaseInstanceSetup.ColorForText = instanceSetup.ColorForText;
                databaseInstanceSetup.ColorForHeader = instanceSetup.ColorForHeader;
                databaseInstanceSetup.ColorForHighlightedArea = instanceSetup.ColorForHighlightedArea;
                databaseInstanceSetup.LogoImageBlobId = instanceSetup.LogoImageBlobId;

                context.SaveChanges();
            }
        }
    }
}


